<template>
  <el-button v-bind="$attrs" :disabled="disabled" @click="handleStart" :loading="loading">{{
    getButtonText
  }}</el-button>
</template>

<script setup>
import { useCountdown } from "./useCountdown";

defineOptions({ name: "CountButton" });

const props = defineProps({
  count: { type: Number, default: 60 },
  beforeStartFunc: {
    type: Function,
    default: null,
  },
});

const loading = ref(false);
const { currentCount, isStart, start, reset } = useCountdown(props.count);

const getButtonText = computed(() => {
  return !unref(isStart) ? "获取验证码" : `${unref(currentCount)}秒后重新获取`;
});
const disabled = computed(() => unref(isStart));

onUnmounted(() => {
  reset();
});

async function handleStart() {
  const { beforeStartFunc } = props;
  if (beforeStartFunc && typeof beforeStartFunc === "function") {
    loading.value = true;
    try {
      const canStart = await beforeStartFunc();
      canStart && start();
    } finally {
      loading.value = false;
    }
  } else {
    start();
  }
}
</script>

<style lang="scss" scoped></style>
